package com.example.service;

import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author yexi
 */
@Component
public class DemoService {


    @Retryable(value = {RuntimeException.class},  // 指定发生的异常进行重试
            maxAttempts = 3,                      // 重试次数, 默认即为3
            backoff = @Backoff(delay = 2000, multiplier = 2)) // 每次重试延迟毫秒数 及 延迟倍数
    public void doSomething() {
        System.out.println("开始处理业务，当前时间是: " + new Date().toLocaleString());
        System.out.println("即将模拟业务处理出现异常");
        throw new RuntimeException("业务处理出现异常，抛出");
    }

    @Recover
    public void recover(RuntimeException e) {
        System.out.println("多次重试后，业务处理仍然失败，当前时间是: " + new Date().toLocaleString());
        e.printStackTrace();
    }

    @Retryable(value = {RuntimeException.class},
            maxAttempts = 2,
            backoff = @Backoff(delay = 2000, multiplier = 1))
    public String doSomething2(int code) {
        System.out.println("开始处理业务2，当前时间是: " + new Date().toLocaleString());
        if (code == 0) {
            throw new RuntimeException("业务2处理出现异常，抛出");
        }
        return "业务2处理成功，返回处理值";
    }

    @Recover
    public String recover2(RuntimeException e) {
        System.out.println("多次重试后，业务2处理仍然失败，当前时间是: " + new Date().toLocaleString());
        e.printStackTrace();
        return "返回业务2处理失败的默认值";
    }


}
